package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-13 22:25
 **/

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;


    /*
    * 查询动态评论  (动态id，互动类型 = 2 )
    * */
    public PageResult findComments(String movementId, Integer page, Integer pageSize) {
        Integer commentType = 2;//评论
        //根据动态id，互动类型，分页查询评论数据  list<Comment>
        List<Comment> list = commentApi.findComments(movementId,commentType,page,pageSize);
        //2.判断Comment是否为空
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //一次性获取所有评论列表中的评论人

        //一次性查询所有评论人
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        //调用api,一次性获取所有评论列表中的评论人的信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        //3.循环一个List<Comment>,一个Comment构建一个vo
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            //获取互动操作人
            Long userId = comment.getUserId();
            UserInfo info = map.get(userId);
            CommentVo vo = CommentVo.init(info, comment);//评论发布人信息，互动对象
            vos.add(vo);
        }


        //4.返回
        return new PageResult(page,pageSize,0L,vos);
    }

    //保存互动评论数据
    public void saveComment(String movementId, String content) {
        Integer commentType = 2 ;
        //1.创建Comment对象，设置属性值
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(commentType);
        comment.setContent(content);
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        //2.调用API保存，保存后返回评论总数
        Integer count = commentApi.save(comment);
        System.out.println("评论总数="+count);

    }
}
